import { post, get } from '../../utils/request';
import { fetchSSE } from '@/utils/fetch';

// 定义接口响应类型
interface ChatResponse {
  code: number;
  msg: string;
  status: boolean;
  data: any;
  fail: boolean;
}

/**
 * 检查智能体状态
 * @param params 请求参数
 * @returns Promise<ChatResponse>
 */
export const checkChat = (params: any): Promise<ChatResponse> => {
  return post<ChatResponse>('/api/chat/checkChat', params);
}

/**
 * 调用聊天
 * @param params 请求参数
 * @returns Promise<ChatResponse>
 */
export const callChat = (params: any): Promise<ChatResponse> => {
  return post<ChatResponse>('/api/chat/callChat', params);
}

/**
 * 调用流式聊天
 * @param params 请求参数
 * @returns Promise<ChatResponse>
 */
export const callChatStream = (params: any): Promise<ChatResponse> => {
  return post<ChatResponse>('/api/chat/callChatStream', params);
}

/**
 * 获取流式聊天会写消息
 * @param params 请求参数
 * @returns Promise<ChatResponse>
 */
export const getChatMessage = (params: any): Promise<ChatResponse> => {
  return post<ChatResponse>('/api/chat/getChatMessage', params);
}

/**
 * AI对话（非流式）
 * @param params { sessionId, userMessage, agentId, additionalParams, promptName, functionName }
 * @returns Promise<ChatResponse>
 */
export const callAIChat = (params: any, signal?: AbortSignal): Promise<ChatResponse> => {
  return post<ChatResponse>('/api/starhub/chat/call', params, undefined,signal);
}

/**
 * 获取智能体信息
 * @param params 请求参数
 * @returns Promise<ChatResponse>
 */
export const getAgentInfo = (params: any): Promise<ChatResponse> => {
  return get<ChatResponse>('/api/starhub/chat/initAgent', params);
}

/**
 * 获取流式聊天会写消息
 * @param params 请求参数
 * @param onAbort 
 * @param onMessageHandle 
 * @param onFinish 
 * @param signal 
 * @returns 
 */
export const getChatMessageStream = (
  params: any, 
  onAbort: (text: string) => void, 
  onMessageHandle: (chunk: any) => void, 
  onFinish: (text: string) => void,
  signal?: AbortSignal
): Promise<any> => {
  const token = localStorage.getItem('token');
  return fetchSSE(`/api/starhub/chat/callStream`, {
    method: 'post',
    body: JSON.stringify(params),
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`,
    },
    signal,
    onAbort: async (text) => {
      onAbort(text);
    },
    onMessageHandle: async (chunk) => {
      onMessageHandle(chunk);
    },
    onFinish: async (text) => {
      onFinish(text);
    }
  })
}
  
